package com.example.loginpage.ChatAPI

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException
import org.json.JSONObject
import java.util.concurrent.TimeUnit

class ChatViewModel: ViewModel() {
    private val _accessToken = MutableLiveData<String>()
    val accessToken: LiveData<String> = _accessToken
    private val _lastResponse = MutableLiveData<String>()
    val lastResponse: LiveData<String> = _lastResponse
    var allAsking: ArrayList<String> = ArrayList()
    var allAnswer: ArrayList<String> = ArrayList()
    fun clearResponse(){
        _lastResponse.postValue("null")
    }
    fun getAccess(){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val token = getAccessToken()
                withContext(Dispatchers.Main) {
                    _accessToken.postValue(token.toString())
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    e.printStackTrace()
                }
            }
        }
    }
    private fun getAccessToken() : String? {
        val url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=oWSxh2PDYE2veMM6l0w7aphH&client_secret=J4WIh7eSvpVyDJxyvGoJ2Xqr1bTmgE7K"
        val client = OkHttpClient()

        val request = Request.Builder()
            .url(url)
            .post("".toRequestBody(null))
            .build()

        try {
            val response = client.newCall(request).execute()
            if (response.isSuccessful) {
                val responseBody = response.body?.string()
                val json = responseBody?.let { JSONObject(it) }
                if (json != null) {
                    return json.getString("access_token")
                }
            } else {
                println("Request failed: ${response.code}")
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    fun sendRequest(accessToken: String, model: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val response = sendRequestToServer(accessToken,model)
                withContext(Dispatchers.Main) {
                    _lastResponse.postValue(response.toString())
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    e.printStackTrace()
                }
            }
        }
    }
    private fun sendRequestToServer(question: String, model: String) :String?{
        val url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${model}?access_token=${accessToken.value.toString()}"
        val payload = """
{
    "messages": [
        {
            "role": "user",
            "content": "$question"
        }
    ]
}
        """

        val client = OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS) // 连接超时时间
            .readTimeout(60, TimeUnit.SECONDS)    // 读取超时时间
            .writeTimeout(60, TimeUnit.SECONDS)   // 写入超时时间
            .build()
        val request = Request.Builder()
            .url(url)
            .post(payload.toRequestBody())
            .build()

        try {
            val response: Response = client.newCall(request).execute()
            if (response.isSuccessful) {
                val responseBody = response.body?.string()
                val json = responseBody?.let { JSONObject(it) }
                if (json != null) {
                    return json.getString("result")
                }
            } else {
                println("Error: ${response.code}")
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }
}